﻿/*
Copyright © 2011 Nokia Corporation. All rights reserved.
Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation. 
Java and all Java-based marks are trademarks or registered trademarks of 
Sun Microsystems, Inc. Other product and company names mentioned herein may be 
trademarks or trade names of their respective owners.

Subject to the conditions below, you may, without charge:

·  Use, copy, modify and/or merge copies of this software and 
   associated content and documentation files (the “Software”)

·  Publish, distribute, sub-licence and/or sell new software 
   derived from or incorporating the Software.

Some of the documentation, content and/or software maybe licensed under open source software or other licenses.  To the extent such documentation, content and/or software are included, licenses and/or other terms and conditions shall apply in addition and/or instead of this notice. The exact terms of the licenses, disclaimers, acknowledgements and notices are reproduced in the materials provided.

This file, unmodified, shall be included with all copies or substantial portions
of the Software that are distributed in source code form.

The Software cannot constitute the primary value of any new software derived 
from or incorporating the Software.

Any person dealing with the Software shall not misrepresent the source of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Controls.Primitives;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Controls.Maps;


using System.Device.Location;
using System.Collections.ObjectModel;

using Carpool.Bing.Geocode;
using Carpool.Bing.Route;
using Carpool.Bing.Search;

using System.ComponentModel;

namespace Carpool
{
    public partial class MainPage : PhoneApplicationPage
    {
        internal static String datacloudurl = "";
        internal static bool uselastlogin = false;
        internal static bool logindone = false;

        // User profile 
        internal static String username = "";
        internal static String userpassword = "";
        internal static String userkarpoid = "";
        internal static String userfirstname = "";
        internal static String userlastname = "";
        internal static String userhometown = "";
        internal static String userphone = "";
        internal static String useralias = "";
        // Privacy settings
        internal static bool usershowname = false;
        internal static bool usershowphone = false;
        internal static bool usershowhometown = false;

        // carpool activation, i.e. GPS on / GPS off see dccarpoolactivation.active "1" or "0"
        internal static DCCarPoolActivation dccarpoolactivation = null;
        static bool sendingthenewlocation = false;
        private BackgroundWorker locationsaver = new BackgroundWorker();
        static bool locationsaverstarted = false;
        static bool sendgpsstarted = false;
        static GeoCoordinateWatcher geowatcher = null;


        internal static MainPage main = null;
        internal static Map mainmap = null;
        internal static String appcase = "loginfailed";
        internal static String appcasesub = ""; // used in dialog internally, see MyTrips

        internal KarpoDialog activeDialog = null;

        internal static SolidColorBrush ButtonReleasedColor = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0));
        internal static SolidColorBrush ButtonPressedColor = new SolidColorBrush(Color.FromArgb(255, 57, 113, 145)); // "#397191"
        internal static SolidColorBrush ButtonPressedColorGreen = new SolidColorBrush(Color.FromArgb(255, 0, 255, 0));
        internal static SolidColorBrush TitleColor = new SolidColorBrush(Color.FromArgb(255, 0, 0, 139)); // "#00008b"
        internal static SolidColorBrush SelecteAreaColor = new SolidColorBrush(Color.FromArgb(255, 144, 238, 144));
        internal static SolidColorBrush BlackColor = new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));
        internal static SolidColorBrush WhiteColor = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255));


        internal readonly CredentialsProvider _credentialsProvider = new ApplicationIdCredentialsProvider(App.BingMapsKey);
 

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            main = this;
       }



        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            MainPage.mainmap = map;
            //MainPage.msgbox = messagebox;

            checkTheSettings();

            if ((Application.Current as Carpool.App).restoreui != null && (Application.Current as Carpool.App).restoreui.appcase == "carpool")
            {
                handleMenuSelection("Carpools...");
            }
            else if ((Application.Current as Carpool.App).restoreui != null && (Application.Current as Carpool.App).restoreui.appcase == "joinrequest")
            {
                (Application.Current as Carpool.App).restoreui = new RestoreUI("empty");
                resetMenu();
            }
            else
            {
                if (datacloudurl.Length == 0)
                {
                    handleMenuSelection("Settings...");
                }
                else if (!uselastlogin)
                {
                    handleMenuSelection("Login...");
                }
                else
                {
                    resetMenu();
                }
            }

            // Check if the bing maps key is set
            if (String.IsNullOrEmpty(App.BingMapsKey))
            {
                MessageBox.Show("The BingMapsKey in the App.xaml.cs is not set. The bing maps services can't be used.");
            }

        }


        internal void sendGPS(string state)
        {
            if (state.CompareTo("start") == 0)
            {
                sendingthenewlocation = false;
                sendgpsstarted = true;
                // start receiving
                if (!locationsaverstarted)
                {
                    try
                    {
                        KarpoMessageBox.showMessageBox("Starting the gps receiver...");
 
                        geowatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
                        geowatcher.MovementThreshold = 50;
                        geowatcher.StatusChanged += (s, e) =>
                            {
                                if (!locationsaverstarted && sendgpsstarted)
                                {
                                    if (e.Status == GeoPositionStatus.Disabled)
                                    {
                                        KarpoMessageBox.hideMessageBox();
                                        MessageBox.Show("Please enable your location service by going to Settings -> Location -> Turn on Location Service option.");
                                        sendGPS("stop");
                                    }
                                    else
                                    {
                                        KarpoMessageBox.hideMessageBox();
                                        // start the location receiver thread
                                        locationsaver.WorkerReportsProgress = true;
                                        locationsaver.WorkerSupportsCancellation = true;
                                        locationsaver.DoWork += new DoWorkEventHandler(locationsaver_DoWork);
                                        locationsaver.RunWorkerAsync();
                                        locationsaverstarted = true;

                                        // show the gps icon
                                        gpsicon.Visibility = Visibility.Visible;
                                    }
                                }
                            };

                        geowatcher.Start(true);

                    }
                    catch (Exception ex)
                    {
                       KarpoMessageBox.showMessageBox("Ex:" + ex.Message);
                    }
                }
            }
            else
            {
                sendgpsstarted = false;
                if (locationsaverstarted)
                {
                    // stop receiving
                    geowatcher.Stop();
                    locationsaver.CancelAsync();
                    locationsaverstarted = false;
                }
                // hide the gps icon
                gpsicon.Visibility = Visibility.Collapsed;
            }
        }

        private void locationsaver_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            bool dowork = true;

            int waitms = 100;
            int counterfrom = 50; // counterfrom * waitms = 5 sec
            int counter = 0;
            while (dowork)
            {
                if ((worker.CancellationPending == true))
                {
                    e.Cancel = true;
                    dowork = false;
                }
                else
                {
                    if (!sendingthenewlocation)
                    {

                        GeoCoordinate coord = geowatcher.Position.Location;

                        if (coord.IsUnknown != true)
                        {
                            sendingthenewlocation = true;
                            string lat = coord.Latitude.ToString();
                            string lon = coord.Longitude.ToString();
                            MainPage.main.carpool.setcarpoolactivation(dccarpoolactivation.carpoolkarpoid, "1", lat, lon, dccarpoolactivation.alias);
                            counter = counterfrom;
                        }
                        else
                        {
                            counter = 5; // just half second
                        }
                    }
                    else
                    {
                        counter = 10; // a second
                    }

                    while (counter > 0 && dowork)
                    {
                        System.Threading.Thread.Sleep(waitms);
                        counter--;
                    }
                }
            }
        }            


        internal void IndicateNewMessage(Boolean newmessage)
        {
            messageicon.Visibility = (newmessage ? Visibility.Collapsed : Visibility.Visible);
            messagenewicon.Visibility = (newmessage ? Visibility.Visible : Visibility.Collapsed);

        }

        // load settings and personal data from the local database
        internal void checkTheSettings()
        {

            var settings = IsolatedStorageSettings.ApplicationSettings;
            if (settings.Contains("datacloudurl"))
                datacloudurl = settings["datacloudurl"].ToString();

            if (settings.Contains("uselastlogin"))
                uselastlogin = (settings["uselastlogin"].ToString() == "yes");
            
            if (settings.Contains("logindone"))
                logindone = (settings["logindone"].ToString() == "yes");
            
            if (settings.Contains("username"))
                username = settings["username"].ToString();
            
            if (settings.Contains("userpassword"))
                userpassword = settings["userpassword"].ToString();
            
            if (settings.Contains("userkarpoid"))
                userkarpoid = settings["userkarpoid"].ToString();
            
            if (settings.Contains("userfirstname"))
                userfirstname = settings["userfirstname"].ToString();
            
            if (settings.Contains("userlastname"))
                userlastname = settings["userlastname"].ToString();
            
            if (settings.Contains("userhometown"))
                userhometown = settings["userhometown"].ToString();
            
            if (settings.Contains("userphone"))
                userphone = settings["userphone"].ToString();
            
            if (settings.Contains("useralias"))
                useralias = settings["useralias"].ToString();
            
            if (settings.Contains("showname"))
                usershowname = (settings["showname"].ToString() == "1" ? true : false);
            
            if (settings.Contains("showphone"))
                usershowphone = (settings["showphone"].ToString() == "1" ? true : false);
            
            if (settings.Contains("showhometown"))
                usershowhometown = (settings["showhometown"].ToString() == "1" ? true : false);

             
        }

        private void Menurect_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Menurect.Background = MainPage.ButtonPressedColor;
        }


        private void Menurect_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Menurect.Background = MainPage.ButtonReleasedColor;
            if (messages.messagesPopup.IsOpen) messages.showMessages(false);
            karpomenu.showMenu();

        }

        private void Menurect_MouseLeave(object sender, MouseEventArgs e)
        {
            Menurect.Background = MainPage.ButtonReleasedColor;
        }

        private void Messagerect_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
             Messagerect.Background = MainPage.ButtonPressedColor;
        }

        private void Messagerect_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Messagerect.Background = MainPage.ButtonReleasedColor;
            messages.showMessages(true);
        }

        private void Messagerect_MouseLeave(object sender, MouseEventArgs e)
        {
            Messagerect.Background = MainPage.ButtonReleasedColor;
        }

        internal void resetMenu()
        {
            appcase = (logindone ? "loginok" : "loginfailed");
            activeDialog = null;
            setWindowTitle("Carpool");

        }

        internal void showCrosshair(bool visible)
        {
            crosshair.Visibility = (visible ? Visibility.Visible : Visibility.Collapsed);

        }

        private void crosshair_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            crosshair.Background = ButtonPressedColorGreen;
        }

        private void crosshair_MouseLeave(object sender, MouseEventArgs e)
        {
            crosshair.Background = ButtonReleasedColor;
        }
        private void crosshair_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            crosshair.Background = ButtonReleasedColor;
            if (activeDialog != null)
            {
                // calculate the middle of the crosshair
                Point pos1 = e.GetPosition(crosshair);
                Point pos2 = e.GetPosition(mainmap);
                Point pos = new Point(pos2.X - (pos1.X - 24), pos2.Y - (pos1.Y - 24));

                GeoCoordinate geo = map.ViewportPointToLocation(pos);
                activeDialog.crosshairLocation(geo.Latitude, geo.Longitude);
            }
        }

        internal void setWindowTitle(String title)
        {
            MainTitle.Margin = new Thickness(10);
            MainTitle.Text = title;
            MainTitle.HorizontalAlignment = HorizontalAlignment.Left;
            MainTitle.TextAlignment = TextAlignment.Center;
            MainTitle.VerticalAlignment = VerticalAlignment.Center;

            MainTitle.FontFamily = new FontFamily("Arial");
            MainTitle.FontSize = 24;
            MainTitle.Foreground = TitleColor;



        }


        internal void setFromToAddress(String fromaddress, String toaddress)
        {
            if (fromaddress == null || toaddress == null)
            {
                FromAddress.Text = "";
                ToAddress.Text = "";
                FromToAddresses.Visibility = Visibility.Collapsed;
            }
            else
            {
                FromAddress.Text = fromaddress;
                ToAddress.Text = toaddress;
                FromToAddresses.Visibility = Visibility.Visible;
            }
        }


        // This is called from the KarpoMenu
        internal void handleMenuSelection(String selection)
        {

            if (activeDialog != null)
            {
                activeDialog.menuCommand(selection);
            }
            else if (selection == "Carpools...")
            {
                appcase = "carpool";
                activeDialog = carpool;
                carpool.showDialog(true);
            }
            else if (selection == "Routes...")
            {
                appcase = "handleroute";
                activeDialog = routetool;
                
                routetool.showDialog(true);

            }
            else if (selection == "Join trip...")
            {
                appcase = "jointrip";
                activeDialog = jointrip;
                jointrip.showDialog(false);
            }
            else if (selection == "My trips...")
            {
                appcase = "mytrips";
                activeDialog = mytrips;
                mytrips.showDialog(false);
            }
            else if (selection == "Profile...")
            {
                appcase = "profile";
                activeDialog = personalprofile;
                personalprofile.showDialog(true);
            }
            else if (selection == "Settings...")
            {
                appcase = "settings";
                activeDialog = karposettings;
                karposettings.showDialog(true);
 
            }
            else if (selection == "Login...")
            {
                appcase = "login";
                activeDialog = karpologin;
                karpologin.showDialog(true);
            }
        }



        public CredentialsProvider KarpoCredentialsProvider
        {
            get { return _credentialsProvider; }
        }


        private void map_MapPan(object sender, MapDragEventArgs e)
        {
            if (activeDialog == jointrip && maptool.drawingarea)
            {
                // prevent to mouse from moving the map => an area is drawing
                e.Handled = true;
            }
            else
            {
                e.Handled = false;
            }
        }


        double startx = 0.0;
        double starty = 0.0;
        double lastx = -1.0;
        double lasty = -1.0;
        bool mousedown = false;
        


        private void map_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (activeDialog == jointrip && maptool.drawingarea)
            {
                // prevent to mouse from moving the map => an area is drawing
                mousedown = true;

                Point p = e.GetPosition(MapView);
                lastx = p.X;
                lasty = p.Y;

                selectareaTransform.X = lastx;
                selectareaTransform.Y = lasty; 
                
                selectarea.Width = 1;
                selectarea.Height = 1;


                startx = lastx;
                starty = lasty;

                selectarea.Visibility = Visibility.Visible;
            }

            e.Handled = false;

        }

        private void map_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (activeDialog == jointrip && maptool.drawingarea)
            {
                // prevent the mouse from moving the map => an area is drawing
                mousedown = false;
                lastx = -1;
                lasty = -1;
            }

            e.Handled = false;

        }

        private void map_MouseMove(object sender, MouseEventArgs e)
        {
            if (activeDialog == jointrip && maptool.drawingarea && mousedown)
            {
                Point p = e.GetPosition(MapView);
                var dx = p.X - lastx;
                var dy = p.Y - lasty;
                lastx = p.X;
                lasty = p.Y;
                if (lastx < startx)
                {
                    selectareaTransform.X = lastx;
                    selectarea.Width = startx - lastx;
                }
                else
                {
                    selectarea.Width = lastx - startx;
                }
                if (lasty < starty)
                {
                    selectareaTransform.Y = lasty;
                    selectarea.Height = starty - lasty;
                }
                else
                {
                    selectarea.Height = lasty - starty;
                }

            }

        }

        private void PhoneApplicationPage_OrientationChanged(object sender, OrientationChangedEventArgs e)
        {
            KarpoMessageBox.orientationChanged(e);
        }

        private void PhoneApplicationPage_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            double h = e.NewSize.Height;
            double w = e.NewSize.Width;

            carpool.mainpageSizeChanged(w, h);
            karpomenu.mainpageSizeChanged(w, h);
            karpologin.mainpageSizeChanged(w, h);
            karposettings.mainpageSizeChanged(w, h);
            personalprofile.mainpageSizeChanged(w, h);
            messages.mainpageSizeChanged(w, h);

        }


    }
}
